// ==UserScript==
// @name         问财选股-全场景监控+功能整合
// @namespace    http://tampermonkey.net/
// @version      2.6
// @description  监控span内容、分页、列表项点击，智能延迟执行
// @author       豆包
// @match        https://www.iwencai.com/unifiedwap/result?*querytype=stock*
// @icon         https://www.iwencai.com/favicon.ico
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    let lastProcessedCount = 0;
    let lastTabindexValue = null;
    let lastActiveLi = null;
    let currentPage = 1;
    // 用于跟踪点击后的加载状态
    let isLoadingAfterClick = false;

    // 调整td.checkbox-box宽度
    function adjustCheckboxBoxWidth() {
        const targetTds = document.querySelectorAll('td.checkbox-box');
        targetTds.forEach(td => {
            td.style.width = '40px';
            td.style.minWidth = '40px';
            td.style.maxWidth = '40px';
            td.style.boxSizing = 'border-box';
        });
    }

    // 处理翻页导致错误的元素
    function updateOldElement() {
        const processedElements = document.querySelectorAll('a.eastmoney_link');
        processedElements.forEach(el => {
            const stockCode = el.parentElement.parentElement.nextElementSibling?.textContent || '';
            let newCodeParam = '';
            if (stockCode.startsWith('0') || stockCode.startsWith('3') || stockCode.startsWith('9')) {
                newCodeParam = `0.${stockCode}`;
            } else if (stockCode.startsWith('6')) {
                newCodeParam = `1.${stockCode}`;
            }
            if (newCodeParam) {
                el.href = `https://quote.eastmoney.com/f1.html?newcode=${newCodeParam}`;
            }
        });
        lastProcessedCount = 0;
    }

    // 核心处理逻辑
    function processElements() {
        adjustCheckboxBoxWidth();

        const targetIs = document.querySelectorAll('td.checkbox-box div.td-cell-box i');
        if (targetIs.length === lastProcessedCount) return;
        lastProcessedCount = targetIs.length;

        targetIs.forEach(iTag => {
            if (iTag.dataset.processed) return;
            iTag.dataset.processed = 'true';

            const parentTr = iTag.closest('tr');
            if (parentTr && parentTr.textContent.includes('股票名称')) return;

            const codeMatch = parentTr ? parentTr.textContent.trim().match(/\b\d{6}\b/) : null;
            if (!codeMatch) {
                iTag.remove();
                return;
            }
            const stockCode = codeMatch[0];

            let newCodeParam = '';
            if (stockCode.startsWith('0') || stockCode.startsWith('3') || stockCode.startsWith('9')) {
                newCodeParam = `0.${stockCode}`;
            } else if (stockCode.startsWith('6')) {
                newCodeParam = `1.${stockCode}`;
            } else {
                iTag.remove();
                return;
            }

            const link = document.createElement('a');
            link.href = `https://quote.eastmoney.com/f1.html?newcode=${newCodeParam}`;
            link.textContent = '分时';
            link.target = '_blank';
            link.style.color = '#1E90FF';
            link.style.textDecoration = 'underline';
            link.style.fontSize = '12px';
            link.style.marginLeft = '4px';
            link.className = 'eastmoney_link';

            iTag.after(link);

            setTimeout(() => {
                if (iTag.parentNode) iTag.remove();
            }, 0);
        });
    }

    // 监控li.jsc-list-item的点击事件（智能延迟）
    function monitorListItemClicks() {
        // 监听可能的加载指示器（根据实际页面调整选择器）
        const loadingIndicatorSelector = 'div.table-loading > div.is-loading';

        // 事件委托监听点击
        document.addEventListener('click', function(e) {
            const listItem = e.target.closest('li.jsc-list-item');
            if (listItem) {
                isLoadingAfterClick = true;
                console.log('检测到列表项点击，等待加载完成...');

                // 启动轮询检测加载状态
                const checkLoadingTimer = setInterval(() => {
                    // 检查是否存在加载指示器
                    const loadingIndicators = document.querySelectorAll(loadingIndicatorSelector)[0];
                    const loadinigElement = loadingIndicators.parentElement;
                    const loadingStyle = loadinigElement.style.display;

                    const isLoading = loadingStyle == 'none';

                    // 如果没有加载指示器，且距离点击已超过最小延迟（确保稳定性）
                    if (isLoading && Date.now() - clickTime > 400) {
                        clearInterval(checkLoadingTimer);
                        isLoadingAfterClick = false;
                        console.log('点击后加载完成，执行处理...');
                        updateOldElement();
                        processElements();
                    }
                }, 100); // 每100ms检查一次

                // 记录点击时间
                const clickTime = Date.now();

                // 安全超时机制（防止无限等待）
                setTimeout(() => {
                    if (isLoadingAfterClick) {
                        clearInterval(checkLoadingTimer);
                        isLoadingAfterClick = false;
                        console.log('超时，强制执行处理...');
                        updateOldElement();
                        processElements();
                    }
                }, 3000); // 5秒超时
            }
        }, true);
    }

    // 监控span内容变化
    function monitorSpanChanges() {
        const targetSpan = document.querySelector('span.ui-f24.ui-fb.red_text.ui-pl8');
        if (!targetSpan) {
            setTimeout(monitorSpanChanges, 1000);
            return;
        }

        const spanObserver = new MutationObserver((mutations) => {
            mutations.forEach(mutation => {
                if ((mutation.type === 'childList' || mutation.type === 'characterData') && !isLoadingAfterClick) {
                    updateOldElement();
                    processElements();
                }
            });
        });

        spanObserver.observe(targetSpan, {
            childList: true,
            subtree: true,
            characterData: true
        });
    }

    // 监控分页active类
    function monitorPaginationActiveClass() {
        const targetUl = document.querySelector('ul.pcwencai-pagination');
        if (!targetUl) {
            setTimeout(monitorPaginationActiveClass, 1000);
            return;
        }

        lastActiveLi = targetUl.querySelector('li.active');
        if (lastActiveLi) {
            currentPage = parseInt(lastActiveLi.textContent.trim()) || 1;
        }

        const activeObserver = new MutationObserver((mutations) => {
            mutations.forEach(mutation => {
                if (mutation.target.tagName === 'LI' && !isLoadingAfterClick) {
                    const currentActiveLi = targetUl.querySelector('li.active');
                    if (currentActiveLi && currentActiveLi !== lastActiveLi) {
                        const newPage = parseInt(currentActiveLi.textContent.trim()) || 1;
                        if (newPage !== currentPage) {
                            currentPage = newPage;
                            lastActiveLi = currentActiveLi;
                            updateOldElement();
                            setTimeout(() => processElements(), 300);
                        }
                    }
                }
            });
        });

        activeObserver.observe(targetUl, {
            childList: true,
            subtree: true,
            attributes: true,
            attributeFilter: ['class']
        });
    }

    // 监控分页tabindex变化
    function monitorPaginationTabindex() {
        const targetA = document.querySelector('ul.pcwencai-pagination li:first-child a');
        if (!targetA) {
            setTimeout(monitorPaginationTabindex, 1000);
            return;
        }

        lastTabindexValue = targetA.getAttribute('tabindex');
        const paginationObserver = new MutationObserver((mutations) => {
            mutations.forEach(mutation => {
                if (mutation.attributeName === 'tabindex' && !isLoadingAfterClick) {
                    const currentTabindex = targetA.getAttribute('tabindex');
                    if (currentTabindex !== lastTabindexValue) {
                        lastTabindexValue = currentTabindex;
                        updateOldElement();
                        processElements();
                    }
                }
            });
        });

        paginationObserver.observe(targetA, {
            attributes: true,
            attributeFilter: ['tabindex']
        });
    }

    // 初始化
    function init() {
        processElements();
        monitorSpanChanges();
        monitorPaginationActiveClass();
        monitorPaginationTabindex();
        monitorListItemClicks();
    }

    window.onload = function() {
        const checkInterval = 100;
        const checkTimer = setInterval(() => {
            const targetSpan = document.querySelector('span.ui-f24.ui-fb.red_text.ui-pl8');
            if (targetSpan) {
                clearInterval(checkTimer);
                console.log('目标元素已找到，开始执行代码...');
                init();
            }
        }, checkInterval);
    }

})();